﻿using EnvDTE;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Axiom.CodeManifold
{
	public static class CodeModelExtensions
	{
		public static IList<T> GetEntities<T>(this FileCodeModel model) where T : class
		{
			IList<T> result = new List<T>();

			foreach (CodeElement element in model.CodeElements)
			{
				result = GetEntitiesRecoursive<T>(element, result);
			}

			return result;
		}

		private static IList<T> GetEntitiesRecoursive<T>(CodeElement element, IList<T> result) where T : class
		{
			List<vsCMElement> kind = new List<vsCMElement>() { vsCMElement.vsCMElementClass };

			switch (typeof(T).Name)
			{
				case "CodeType":
					kind = new List<vsCMElement>() { vsCMElement.vsCMElementClass, vsCMElement.vsCMElementInterface };
					break;
				case "CodeInterface":
					kind = new List<vsCMElement>() { vsCMElement.vsCMElementInterface };
					break;
				case "CodeNamespace":
					kind = new List<vsCMElement>() { vsCMElement.vsCMElementClass };
					break;
				default:
					break;
			}

			if (kind.Any(a => a == element.Kind))
			{
				result.Add(element as T);
			}

			foreach (CodeElement child in element.Children)
			{
				if (kind.Any(a => a == child.Kind))
				{
					result.Add(child as T);
				}
				else
				{
					GetEntitiesRecoursive<T>(child, result);
				}
			}

			return result;
		}
	}
}
